package asedra.huyle.dao;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import asedra.huyle.dto.Match;

public class MatchDao extends BaseDao<Match>{

	public MatchDao(Context context, String databaseName) {
		super(context, databaseName);
	}

	public MatchDao(SQLiteDatabase db) {
		super(db);
	}

	public MatchDao(SQLiteOpenHelper helper) {
		super(helper);
	}
	
	public long insert(Match match) {
        ContentValues values = new ContentValues();
        values.put(Match.MATCH_ID, match.getMatchId());
        String dateStr = match.getDate().toGMTString();
        values.put(Match.DATE, dateStr);
        values.put(Match.DESCRIPTION, match.getDescription());
        values.put(Match.TITLE, match.getTitle());
        long result = super.insert(Match.TABLE_NAME, values);
        if(result>0)
        	match.setMatchId((int)result);
        return result;
    }


    public long delete(Match match) {
    	ContentValues contentValues = new ContentValues();
    	contentValues.put(Match.MATCH_ID, match.getMatchId());
        long count = super.delete(Match.TABLE_NAME, contentValues);
        return count;
    }
    
    public ArrayList<Match> getAll(){
    	Cursor c = super.getAll(Match.TABLE_NAME, Match.DEFAULT_SORT_ORDER);
    	ArrayList<Match> array = new ArrayList<Match>();
    	if(c==null)
    		return array;
    	while(!c.isAfterLast()){
    		array.add(new Match(c));
    		c.moveToNext();
    	}
    	c.close();
    	return array;
    }
    
    public Match find(final int matchId) {
        ContentValues values = new ContentValues();
        values.put(Match.MATCH_ID, matchId);
        Cursor c = super.find(Match.TABLE_NAME, values,Match.DEFAULT_SORT_ORDER);
        Match student = null;
        if (c != null) {
            try {
            	student = new Match(c);
            } catch (Exception e) {
            	e.printStackTrace();
			}
            finally {
                c.close();
            }
        }
        return student;
    }
    
    public boolean update(Match match){
    	boolean flag = true;
        ContentValues values = new ContentValues();
        String dateStr = match.getDate().toGMTString();
        values.put(Match.DATE, dateStr);
        values.put(Match.DESCRIPTION, match.getDescription());
        values.put(Match.TITLE, match.getTitle());
    	flag = super.update(Match.TABLE_NAME, values, Match.MATCH_ID + "=?", new String[]{String.valueOf(match.getMatchId())})>0;
    	return flag;
    }

}
